const createError = require('http-errors');
const express = require('express');
const path = require('path');
const logger = require('morgan');
const favicon = require('serve-favicon');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const session = require('express-session');

const router = require('./routes/index');

const app = express();

app.use(session({
  secret: 'bin-secret',
  name: 'bin-name',
  cookie: {maxAge: 8000000000},
  resave: false,
  saveUninitialized: true
}));

app.use(function (req, res, next) {
  var url = req.originalUrl;
  if (!req.session.employee
      && ((url.indexOf('/admin') > -1 && url.indexOf('.html') > -1) || url == '/admin/' )
      && url.indexOf('/admin/login.html') == -1) {
      return res.redirect('/admin/login.html');
  }
  next();
});

// app.use(favicon(path.join(__dirname, 'public/mobile/img', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', router);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.send('error');
});

module.exports = app;
